<?php
/**
 * Created by PhpStorm.
 * User: luzy
 * Date: 2018/6/27
 * Time: 上午11:29
 */

class Mp_model extends Base_Model
{
    private $_appid;
    private $_appsecret;
    private $_mpid;

    public function __construct()
    {
        parent::__construct();
    }

    public function getAccessToken()
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $token = $redis->get($this->_mpid.'_access_token');
        if ($token===false){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret;
            $res = $this->http_request($url);
            $res = json_decode($res,true);
            $redis->set($this->_mpid.'_access_token',$res['access_token'],6000);
            return $res['access_token'];
        }else{
            return $token;
        }
    }

    public function setAppParams($mpid)
    {
        $this->config->load('weixin');
        $this->_appid=$this->config->item($mpid.'_appid');
        $this->_appsecret=$this->config->item($mpid.'_appsecret');
        $this->_mpid = $mpid;
    }

    public function sendMsg($openid,$tempid,$tempdata,$formid,$page='')
    {
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$token;
        $data = array('touser'=>$openid,'template_id'=>$tempid,'page'=>$page,'form_id'=>$formid,'data'=>$tempdata);
        $data = json_encode($data);
//        log_message('error',$data);
        $this->http_request($url,$data);
//        log_message('error',$res);
    }

    public function jscode2session($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->_appid."&secret=".$this->_appsecret."&js_code=".$code."&grant_type=authorization_code";
        $res = $this->http_request($url);
        return json_decode($res,true);
    }

    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    protected function http_request($url, $data = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function getUid($sessiondata,$mpid)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $uid = $redis->get('mpuser:'.$mpid.':'.$sessiondata['openid'].':uid');

        if ($uid===false){
            $this->load->database();
            $res = $this->db->get_where('mod_mp_openid',array('openid'=>$sessiondata['openid'],'source'=>$mpid),1,0)->row_array();
            if (empty($res)){
                //用户不存在
                $unionid = isset($sessiondata['unionid'])?$sessiondata['unionid']:'';
                if ($this->db->insert('mod_mp_user',array('unionid'=>$unionid,'created'=>time(),
                    'changed'=>time(),'status'=>1,'userToken'=>md5($sessiondata['openid'])))){
                    $uid=$this->db->insert_id();
                    $this->db->insert('mod_mp_userinfo',array('uid'=>$uid));
                    $this->db->insert('mod_mp_openid',array('uid'=>$uid,'openid'=>$sessiondata['openid'],'source'=>$mpid));
                    $redis->set('mpuser:'.$mpid.':'.$sessiondata['openid'].':uid',$uid);
                    return $uid;
                }else{return false;}
            }else{$redis->set('mpuser:'.$mpid.':'.$sessiondata['openid'].':uid',$res['uid']);return $res['uid'];}

        }else{return $uid;}
    }

    public function addUserInfo($uid,$userinfo)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $this->load->database();

        $isregister = $redis->getBit('mpuser:userinfo:register',$uid);
        //是否录入过信息
        if ($isregister===0) {
            //用户是否存在
            $res = $this->db->get_where('mod_mp_user',array('uid'=>$uid),1,0)->row_array();
            if (!empty($res)){
                $userinfo['nickName']=preg_replace_callback('/./u', function (array $match) {return strlen($match[0]) >= 4 ? '' : $match[0];}, $userinfo['nickName']);
                $udata=array(
                    'userIcon'=>$userinfo['avatarUrl'],
                    'userName'=>$userinfo['nickName'],
                );
                $uidata=array(
                    'userGender'=>$userinfo['gender']==1?'m':($userinfo['gender']==2?'f':''),
                    'city'=>$userinfo['city'],
                    'province'=>$userinfo['province'],
                    'country'=>$userinfo['country']
                );
                if ($this->db->update('mod_mp_user',$udata,array('uid'=>$uid))
                    &&$this->db->update('mod_mp_userinfo',$uidata,array('uid'=>$uid))){
                    //信息都更新成功
                    $redis->setBit('mpuser:userinfo:register',$uid,1);
                    return 2;
                }
            }else{return 3;}
        }else{return 1;}
    }
}